package cn.xspace.wnx.fragment;

import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.xspace.android.xafcommon.base.BaseFragment;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.MyListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.activity.ChatInfoActivity;
import cn.xspace.wnx.activity.SelectMemberActivity;
import cn.xspace.wnx.adapter.CommonTreeListAdapber;
import cn.xspace.wnx.adapter.TreeListViewAdapter;
import cn.xspace.library.bean.OrgDeptUserBean;
import cn.xspace.library.view.tree.bean.Node;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by liuchen on 2016/10/28.
 */

public class OrganizationSelectFragment extends BaseFragment {

    private static final String TAG = OrganizationSelectFragment.class.getSimpleName();

    //    private List<OrgDeptUserBean> dataList;
    private MyListView dataListview;
    private String user_id = "";
    private String sum_dept_id = "";

    private List<OrgDeptUserBean> mDataList;
    private CommonTreeListAdapber<OrgDeptUserBean> orgListAdpter;
    private OrgDeptUserBean lastDeptBean = null;
    //存放  机构id -- userList
    //存放从服务器返回的机构成员list,
    private Map<String, List<OrgDeptUserBean>> userListMap;
    //存放某机构下的所有成员，包括内部部门的成员
    private Map<String, List<OrgDeptUserBean>> userOrgListMap;//部门id 对应所有成员对象
    //存放某机构下的所有内部部门对象 一个部门对应一个部门list
    private Map<String, List<OrgDeptUserBean>> deptOrgListMap;//部门id 对应所有成员对象
    private Map<String, List<OrgDeptUserBean>> parentOrgListMap;//部门id 对应所有成员对象
    private List<OrgDeptUserBean> deptBeanList;
    private boolean isBishanSpecial = false;
    /**
     * 请求获取机构的map
     */
//    private Map<String, Object> orgMap;
    private String fromType = "";

    private List<String> lastNodeIdOrg = new ArrayList<>();

    /**
     * 存储加载过的机构的Id
     */
    private HashMap<String, List<OrgDeptUserBean>> orgLoadMap;
    private ArrayList<String> currentUserIdList;
    private boolean isDeptMentChat = true;

    //界面没初始化之前需要存储的用户
    private List<String> saveUndealUser = new ArrayList<>();
    private boolean isInit = false;
    private String lastDepId; //最后一个部门id

    public static OrganizationSelectFragment newInstance(ArrayList<OrgDeptUserBean> dataList, String fromType) {

        Bundle args = new Bundle();
        args.putSerializable(SelectMemberActivity.SELECTED_MEMBERS, dataList);
        args.putString(ChatInfoActivity.KEY_MEMBER_OPERATE, fromType);
        OrganizationSelectFragment fragment = new OrganizationSelectFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View initView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_addressbook_list_select, null);
    }

    @Override
    protected void initFindViewById(View view) {
        dataListview = (MyListView) view.findViewById(R.id.listview_addressbook);
//        orgMap = new HashMap();
        user_id = MyInfoUtil.getMyUserid(mContext);
        sum_dept_id = MyInfoUtil.getUserOrgId();
//        sum_dept_id = MyInfoUtil.getUseOrgId(mContext);
        //用户所在机构name
        String dept_name = MyInfoUtil.getUserOrgName();
//        if (WorklogController.getInstance().iSBiShanAppOrgAndDirect()) {
//            isBishanSpecial = true;
//            //璧山特殊权限，app机构id
//            sum_dept_id = MyInfoUtil.getAppOrgId();
//            LogUtil.d("MyInfoUtil.getAppOrgId>>" + sum_dept_id);
//            //璧山特殊权限，app机构name
//            dept_name = MyInfoUtil.getAppInfo(mContext).app_deptname;
//        } else if (!WorklogController.getInstance().isCanViewAddressbookMyOrg()) {
//            isDeptMentChat = false;
//        }
        //用户所在机构
//        if (isBishanSpecial || isDeptMentChat) {
        mDataList = new ArrayList<>();
        lastDeptBean = new OrgDeptUserBean();
        lastDeptBean.dept_id = sum_dept_id;
        lastDeptBean.dept_name = dept_name;
        lastDeptBean.isLookOrg = false; //是否显示点击进入群组的popupWindow
        mDataList.add(lastDeptBean);
        deptBeanList = new ArrayList<>();
        deptBeanList.add(lastDeptBean);
        try {
            orgListAdpter = new CommonTreeListAdapber<>(dataListview, mContext, mDataList, 0, false, true, false);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        orgListAdpter.setiOrgUserCheckListener(listener);
        dataListview.setAdapter(orgListAdpter);
        orgLoadMap = new HashMap<>();
        userListMap = new HashMap<>();
        userOrgListMap = new HashMap<>();
        deptOrgListMap = new HashMap<>();
        parentOrgListMap = new HashMap<>();
    }


    @Override
    public void initData() {
        fromType = fragmentArgs.getString(ChatInfoActivity.KEY_MEMBER_OPERATE);
        ArrayList<OrgDeptUserBean> currentUserList = (ArrayList<OrgDeptUserBean>) fragmentArgs.getSerializable
                (SelectMemberActivity.SELECTED_MEMBERS);
        currentUserIdList = new ArrayList<>();
        if (currentUserList != null) {
            for (OrgDeptUserBean bean : currentUserList) {
                currentUserIdList.add(bean.user_id);
            }
        }
        //用户所在机构
//        if (isBishanSpecial || isDeptMentChat) {
//            getOrgData();
        getNetWorkData(sum_dept_id);
//        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        if (orgListAdpter != null)
            orgListAdpter.setOnTreeNodeClickListener(new TreeListViewAdapter.OnTreeNodeClickListener() {
                @Override
                public void onClick(Node node, int position, boolean isImg) {
                    commonClickEvent(node, position, isImg);
                }
            });
    }

    /**
     * 暂时无用
     */
    private void findAllParentSelectAll() {
        //寻找所有的父节点
        for (OrgDeptUserBean child : deptBeanList) {
            for (OrgDeptUserBean parent : deptBeanList) {
                //找他们的子节点
                if (child.dept_pid.equals(parent.dept_id)) {
//                    allToDeptMap(deptbean.dept_id, bean);
                    innerParentFind(child.dept_pid,parent);
                    if (parentOrgListMap.containsKey(child.dept_id)) {
                        parentOrgListMap.get(child.dept_id).add(parent);
                    } else {
                        List<OrgDeptUserBean> beanList = new ArrayList<>();
                        beanList.add(parent);
                        parentOrgListMap.put(child.dept_id, beanList);
                    }
                }
            }
        }
    }

    private void innerParentFind(String childId, OrgDeptUserBean childBean) {
            for (OrgDeptUserBean parent : deptBeanList) {
                //找他们的子节点
                if (childBean.dept_pid.equals(parent.dept_id)) {
//                    allToDeptMap(deptbean.dept_id, bean);
                    innerParentFind(childId,parent);
                    if (parentOrgListMap.containsKey(childId)) {
                        parentOrgListMap.get(childId).add(parent);
                    } else {
                        List<OrgDeptUserBean> beanList = new ArrayList<>();
                        beanList.add(parent);
                        parentOrgListMap.put(childId, beanList);
                    }
                }
            }
    }

    /**
     * 监听选择check
     */
    CommonTreeListAdapber.IOrgUserCheckListener listener = new CommonTreeListAdapber.IOrgUserCheckListener() {
        @Override
        public void orgUserCheck(int postion, final OrgDeptUserBean bean, final boolean isChecked) {

            bean.isSelectd = isChecked;
            if (bean.isDeptAllUser) { //选择本机构或者本部门下所有成员的bean
                List<OrgDeptUserBean> sendToUserList = new ArrayList<>(); //发送的用户集合
                addToAllMap();
//                findAllParentSelectAll();
                for (Map.Entry<String, List<OrgDeptUserBean>> entry : userOrgListMap.entrySet()) {
                    //找到对应的部门
                    if (entry.getKey().equals(bean.dept_pid)) {
                        sendToUserList.addAll(entry.getValue());
                        //便利使其状态改变
                        for (OrgDeptUserBean userBean : entry.getValue()) {
                            if( userBean.isCheckBoxEnable){
                                userBean.isSelectd = isChecked;
                            }
                        }
                        break;
                    }

                }
                //处理每个部门的全选按钮
                for (Map.Entry<String, List<OrgDeptUserBean>> entry : deptOrgListMap.entrySet()) {
                    if (entry.getKey().equals(bean.dept_pid)) {
                        for (OrgDeptUserBean allbean : entry.getValue()) {
                            for (OrgDeptUserBean userBean : mDataList) {
                                if (userBean.dept_id.equals(allbean.dept_id + "allSelect")) {
                                    userBean.isSelectd = isChecked;
                                    break;
                                }

                            }
                        }
                        break;
                    }
                }
                //处理上级的全选按钮

                //取消选择，直接将父亲的取消掉
                if (!isChecked) {
                    findAllParentChild(bean);
//                        targetList.addAll(allParentChildList);
//                        allParentChildList.clear();
                    //继续将其父节点的本部门的所有成员取掉
                    for (OrgDeptUserBean targetbean : allParentChildList) {
                        for (OrgDeptUserBean temBean : mDataList) {
                            if (temBean.dept_id.equals(targetbean.dept_id + "allSelect")) {
                                temBean.isSelectd = false;
                                break;
                            }
                        }
                    }
                    allParentChildList.clear();
                }else {
                    addToAllMap();
                    allchildSelect(bean.dept_pid);
                }
                if (orgListAdpter != null)
                    orgListAdpter.notifyDataSetChanged();
                Map<String, Object> toActivityMap = new HashMap<>();
                toActivityMap.put(EventBusConstant.TYPE, EventBusConstant.ORGANIZATION_TO_ACTIVITY);
                toActivityMap.put(EventBusConstant.SELECT_OR_CANCEM, isChecked);
                toActivityMap.put(EventBusConstant.NUMBER_SELECT, EventBusConstant.LIST_MEMBER);
                toActivityMap.put(EventBusConstant.LIST_MEMBER, sendToUserList);
                EventBus.getDefault().post(toActivityMap);
                Map<String, Object> toFragmentMap = new HashMap<>();
                toFragmentMap.put(EventBusConstant.TYPE, EventBusConstant.ORGANIZATION_TO_ADDRESSBOOK);
                toFragmentMap.put(EventBusConstant.SELECT_OR_CANCEM, isChecked);
                toFragmentMap.put(EventBusConstant.NUMBER_SELECT, EventBusConstant.LIST_MEMBER);
                toFragmentMap.put(EventBusConstant.LIST_MEMBER, sendToUserList);
                EventBus.getDefault().post(toFragmentMap);
            } else { //普通的成员bean
                Map<String, Object> toActivityMap = new HashMap<>();
                toActivityMap.put(EventBusConstant.TYPE, EventBusConstant.ORGANIZATION_TO_ACTIVITY);
                toActivityMap.put(EventBusConstant.SELECT_OR_CANCEM, isChecked);
                toActivityMap.put(EventBusConstant.NUMBER_SELECT, EventBusConstant.SINGLE_MEMBER);
                toActivityMap.put(EventBusConstant.SINGLE_MEMBER, bean);
                EventBus.getDefault().post(toActivityMap);
                //通知fragment更新
                Map<String, Object> toFragmentMap = new HashMap<>();
                toFragmentMap.put(EventBusConstant.TYPE, EventBusConstant.ORGANIZATION_TO_ADDRESSBOOK);
                toFragmentMap.put(EventBusConstant.SELECT_OR_CANCEM, isChecked);
                toFragmentMap.put(EventBusConstant.NUMBER_SELECT, EventBusConstant.SINGLE_MEMBER);
                toFragmentMap.put(EventBusConstant.OPERATE_ID, bean.user_id);
                EventBus.getDefault().post(toFragmentMap);

                //将多个id一样的用户操作
                for(OrgDeptUserBean tempBean :mDataList){
                    if(tempBean.dept_id.equals(bean.dept_id)){
                        tempBean.isSelectd = isChecked;
                    }
                }
                judgeParentSelectStatus(bean.dept_id, isChecked);
                orgListAdpter.notifyDataSetChanged();
            }
        }
    };

    /**
     * 判断首位全选的状态
     *
     * @param id
     * @param isChecked
     */
    private void judgeParentSelectStatus(String id, boolean isChecked) {
        long s = SystemClock.currentThreadTimeMillis();
        //找到对应bean
        OrgDeptUserBean userBean = null;
        if (mDataList == null) {
            return;
        }

        List<OrgDeptUserBean> beanList = new ArrayList<>();
        for (OrgDeptUserBean bean : mDataList) {
            if (bean.dept_id.equals(id)) {
//                userBean = bean;
                beanList.add(bean);
            }
        }
//        if (userBean == null) {
//            return;
//        }
        if(beanList.size() == 0){
            return;
        }
        for(OrgDeptUserBean selectBean :beanList){
            deptmentInnerChildHandle(selectBean, null, isChecked);
            long e = SystemClock.currentThreadTimeMillis();
            LogUtil.d(TAG, "wubaojie>>>judgeParentSelectStatus: time:" + (e - s));
        }
    }

    List<OrgDeptUserBean> allParentChildList = new ArrayList<>();

    private void findAllParentChild(OrgDeptUserBean userBean) {
        for (Map.Entry<String, List<OrgDeptUserBean>> entry : userListMap.entrySet()) {
            if (entry.getKey().equals(userBean.dept_pid)) {
                for (OrgDeptUserBean deptbean : deptBeanList) {
                    if (deptbean.dept_id.equals(entry.getKey())) {
                        //找到对应父节点bean,继续找其父节点
                        allParentChildList.add(deptbean);
                        findAllParentChild(deptbean);

                    }
                }
                break;
            }
        }
    }

    private void deptmentInnerChildHandle(OrgDeptUserBean userBean, OrgDeptUserBean curDept, boolean isChecked) {
        long s = SystemClock.currentThreadTimeMillis();
        if (userBean == null) {
            return;
        }
        if (!isChecked) {
            //取消的状态，需要将其所有父节点的全选状态取消掉
            //需要判断的情况为本部门所有成员为选中状态
            for (Map.Entry<String, List<OrgDeptUserBean>> entry : userListMap.entrySet()) {
                if (entry.getKey().equals(userBean.dept_pid)) {
                    //找到用户所在的部门
                    boolean isAllSelect = true;
                    for (OrgDeptUserBean bean : entry.getValue()) {
                        if (!bean.dept_id.equals(userBean.dept_id)) {
                            if (!bean.isSelectd) {
                                //本部门其它有一个节点不选中，则不需要处理
                                isAllSelect = false;
                                break;
                            }
                        }
                    }
                    if (isAllSelect) {
                        findAllParentChild(userBean);
//                        targetList.addAll(allParentChildList);
//                        allParentChildList.clear();
                        //继续将其父节点的本部门的所有成员取掉
                        for (OrgDeptUserBean targetbean : allParentChildList) {
                            for (OrgDeptUserBean bean : mDataList) {
                                if (bean.dept_id.equals(targetbean.dept_id + "allSelect")) {
                                    bean.isSelectd = false;
                                    break;
                                }
                            }
                        }
                        allParentChildList.clear();
                    } else {
                        //本部门其它有一个节点不选中，则不需要处理
                        return;
                    }
                }
            }
        } else {
            //选中的状态
            //临界点为本部门的所有其他子节点为选中状态
            for (Map.Entry<String, List<OrgDeptUserBean>> entry : userListMap.entrySet()) {
                if (entry.getKey().equals(userBean.dept_pid)) {
                    //找到用户所在的部门
                    boolean isAllSelect = true;
                    for (OrgDeptUserBean bean : entry.getValue()) {
                        if (!bean.dept_id.equals(userBean.dept_id)) {
                            if (!bean.isSelectd) {
                                //本部门其它有一个节点不选中，则不需要处理
                                isAllSelect = false;
                                break;
                            }
                        }
                    }
                    if (isAllSelect) {
                        addToAllMap();
                        allchildSelect(userBean.dept_pid);
                        for (OrgDeptUserBean targetbean : mDataList) {
                            if (targetbean.dept_id.equals(userBean.dept_pid + "allSelect")) {
                                targetbean.isSelectd = true;
                                break;
                            }
                        }
                    } else {
                        //本部门其它有一个节点不选中，则不需要处理
                        return;
                    }
                }
            }

        }

    }

    private void allchildSelect(String dep_id) {
        for (Map.Entry<String, List<OrgDeptUserBean>> entry2 : userOrgListMap.entrySet()) {
            if (entry2.getKey().equals(dep_id)) {
                boolean isAllSelect2 = true;
                for (OrgDeptUserBean orgBean : entry2.getValue()) {

                    if (!orgBean.isSelectd) {
                        isAllSelect2 = false;
                        break;
                    }
                }
                if (isAllSelect2) {
                    for (OrgDeptUserBean bean : deptBeanList) {
                        if (bean.dept_id.equals(dep_id)) {
                            for (OrgDeptUserBean bean2 : deptBeanList) {
                                if (bean.dept_pid.equals(bean2.dept_id)) {
                                    //找到其父节点遍历
                                    allchildSelect(bean.dept_pid);
                                    break;
                                }
                            }
                            break;
                        }
                    }
                    //对应部门的所有成员画勾
                    for (OrgDeptUserBean targetbean : mDataList) {
                        if (targetbean.dept_id.equals(dep_id + "allSelect")) {
                            targetbean.isSelectd = true;
                            break;
                        }
                    }
                } else {
                    //继续找上一级
                    return;
                }
                break;
            }
        }

    }
    private void getNetWorkData(final String dep_id) {
        Map<String, Object> orgMap = new HashMap<>();
        orgMap.put("user_id", user_id);
        orgMap.put("dept_id", dep_id);
        LogUtil.d("请求的d dept_id>>>" + dep_id);
        OkHttpManager.getInstance().commonRequest(Constants.QUERY_ORG, orgMap)
                .map(new Func1<BaseReturnBean, List<OrgDeptUserBean>>() {
                    @Override
                    public List<OrgDeptUserBean> call(BaseReturnBean baseReturnBean) {
                        List<OrgDeptUserBean> dataList = new ArrayList<>();
                        LogUtil.d(TAG, "map");
                        JSONObject topJson;
                        JSONArray deptArray;
                        JSONArray userArray;
                        try {
                            topJson = new JSONObject(baseReturnBean.data);
                            userArray = topJson.getJSONArray("userList");
                            //在第一位添加"本部门所有成员"或者"本机构所有成员"的bean
                            if (userArray.length() > 0) {
                                //判断是否本部门全体成员
                                OrgDeptUserBean allUserBean = new OrgDeptUserBean();
                                allUserBean.isLeaf = true;
                                allUserBean.isDeptAllUser = true;
                                allUserBean.dept_id = dep_id + "allSelect";
                                allUserBean.dept_pid = dep_id;
                                LogUtil.e(TAG, "wubaojie>>>" + "call: dep_id:" + dep_id + " & " + sum_dept_id);
                                if (TextUtils.equals(dep_id, sum_dept_id)) {
                                    allUserBean.dept_name = getResources().getString(R.string.all_member_org);
                                } else {
                                    allUserBean.dept_name = getResources().getString(R.string.all_member_dept);
                                }
                                dataList.add(allUserBean);
                                List<OrgDeptUserBean> tempUserList = new ArrayList<>();
                                for (int i = 0; i < userArray.length(); i++) {
                                    OrgDeptUserBean userBean = new OrgDeptUserBean();
                                    JSONObject userJson = userArray.getJSONObject(i);
                                    userBean.dept_pid = dep_id;
                                    userBean.dept_id = userJson.optString("user_id");
                                    userBean.user_id = userJson.optString("user_id");
                                    if (!currentUserIdList.contains(userBean.user_id)) {
                                        allUserBean.isContainDeptAllUser = false;
                                        tempUserList.add(userBean);
                                        break;
                                    }
                                }
                                if (allUserBean.isContainDeptAllUser && tempUserList.size() > 0) {
                                    allUserBean.isSelectd = true;
                                    allUserBean.isCheckBoxEnable = false;
                                }
                            }
                            //添加所有的机构bean
                            deptArray = topJson.getJSONArray("deptList");
                            LogUtil.d("deptArray  " + deptArray.toString());
                            for (int i = 0; i < deptArray.length(); i++) {
                                JSONObject deptJson = deptArray.getJSONObject(i);
                                OrgDeptUserBean deptBean = new OrgDeptUserBean();
                                deptBean.dept_id = deptJson.optString("dept_id");
                                if (i == deptArray.length() - 1) { //最后一个部门了
                                    lastDepId = deptBean.dept_id;
                                }
                                getNetWorkData(deptBean.dept_id);
                                deptBean.dept_name = deptJson.optString("dept_name");
                                deptBean.dept_code = deptJson.optString("dept_code");
                                deptBean.dept_pid = deptJson.optString("dept_pid");
                                deptBean.dept_members = deptJson.optString("dept_members");
                                deptBean.hx_groupid = deptJson.optString("hx_groupid");
                                deptBean.isLeaf = false;
                                deptBean.isLookOrg = false; //右侧点点点不显示
                                deptBeanList.add(deptBean);
                                dataList.add(deptBean);
                            }
                            LogUtil.d("userArray  " + userArray.toString());
                            if (userArray.length() > 0) {
                                List<OrgDeptUserBean> tempUserList = new ArrayList<>();
                                for (int i = 0; i < userArray.length(); i++) {
                                    OrgDeptUserBean userBean = new OrgDeptUserBean();
                                    JSONObject userJson = userArray.getJSONObject(i);
                                    userBean.dept_pid = dep_id;
                                    userBean.dept_id = userJson.optString("user_id");
                                    userBean.user_id = userJson.optString("user_id");
                                    userBean.user_sex = userJson.optString("user_sex");
                                    userBean.dept_name = userJson.optString("user_name");
                                    userBean.user_name = userJson.optString("user_name");
                                    userBean.isMainDept = userJson.optString("user_ismain_job");
                                    userBean.user_logo = userJson.optString("user_logo");
                                    userBean.isLeaf = true;
                                    if (currentUserIdList.contains(userBean.user_id)) {
                                        userBean.isSelectd = true;
                                        userBean.isCheckBoxEnable = false;
                                    }
                                    tempUserList.add(userBean);
                                    dataList.add(userBean);
                                }
                                orgLoadMap.put(dep_id, tempUserList);
                                userListMap.put(dep_id, tempUserList); //所有部门的下属成员的map
                            }
                            LogUtil.d(TAG, "dataList size " + dataList.size());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return dataList;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<OrgDeptUserBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(List<OrgDeptUserBean> orgDeptUserBeen) {
                        LogUtil.d(TAG, "dataList onNext " + orgDeptUserBeen.size());
//            orgLoadMap.put(lastDeptBean.dept_id, orgDeptUserBeen);
                        if (orgDeptUserBeen.size() == 0) {
                            T.show(mContext, getResources().getString(R.string.dept_member_not_exist), Toast
                                    .LENGTH_SHORT);
                            return;
                        }
                        mDataList.addAll(orgDeptUserBeen);
//            lastNodeIdOrg = orgListAdpter.getLastNodeId();
                        orgListAdpter.setData(mDataList, 1);
                        orgListAdpter.notifyDataSetChanged();
                        if (dep_id.equals(lastDepId)) { //当解析完毕最后一个部门集合时,开始处理未处理的用户
                            unDealUser();
                        }
                    }
                });
    }

    private void allToDeptMap(String deptId, OrgDeptUserBean topDeptBean) {
        for (OrgDeptUserBean bean : deptBeanList) {
            //找他们的子节点
            if (bean.dept_pid.equals(topDeptBean.dept_id)) {
                userOrgListMap.get(deptId).addAll(userListMap.get(bean.dept_id));
                allToDeptMap(deptId, bean);
                if (deptOrgListMap.containsKey(deptId)) {
                    deptOrgListMap.get(deptId).add(bean);
                } else {
                    List<OrgDeptUserBean> beanList = new ArrayList<>();
                    beanList.add(bean);
                    deptOrgListMap.put(deptId, beanList);
                }
            }
        }
    }

    private void addToAllMap() {
        if (userOrgListMap.size() != 0) {
            return;
        }
        for (OrgDeptUserBean deptbean : deptBeanList) {
            userOrgListMap.put(deptbean.dept_id, userListMap.get(deptbean.dept_id));
            for (OrgDeptUserBean bean : deptBeanList) {
                //找他们的子节点
                if (bean.dept_pid.equals(deptbean.dept_id)) {
                    allToDeptMap(deptbean.dept_id, bean);
                    if(userListMap.containsKey(bean.dept_id)){
                        userOrgListMap.get(deptbean.dept_id).addAll(userListMap.get(bean.dept_id));
                        if (deptOrgListMap.containsKey(deptbean.dept_id)) {
                            deptOrgListMap.get(deptbean.dept_id).add(bean);
                        } else {
                            List<OrgDeptUserBean> beanList = new ArrayList<>();
                            beanList.add(bean);
                            deptOrgListMap.put(deptbean.dept_id, beanList);
                        }
                    }

                }
            }
        }
    }

    private void unDealUser() {
        isInit = true; //初始化完成了,再发来的消息就不用存了
        for (String userId : saveUndealUser) {
            updateListView(userId, true);
            judgeParentSelectStatus(userId, true);
        }
    }

//    Subscriber<List<OrgDeptUserBean>> orgSubscriber = ;

    /**
     * 点击事件共同处理
     *
     * @param node
     * @param position
     * @param isImg
     */
    private void commonClickEvent(Node node, int position, boolean isImg) {
        LogUtil.d(TAG, "setOnTreeNodeClickListener");
        OrgDeptUserBean orgBean = (OrgDeptUserBean) node.getObject();
        if (orgBean.isLeaf) {
            //叶子节点，跳转到个人名片
            LogUtil.d(TAG, "orgBean.isLeaf");
            return;
        } else {
            LogUtil.d(TAG, "orgBean.isExpand NOT ()");
            if (!checkOrgLoad(orgBean)) {
                LogUtil.d("11");
//                lastDeptBean = orgBean;
//                orgMap.put("dept_id", lastDeptBean.dept_id);
//                //机构打开机构节点
//                getOrgData();
            } else {
                LogUtil.d("22");
                if (orgListAdpter != null)
                    orgListAdpter.expandOrCollapse(position);
            }
        }
    }

    /**
     * 是否加载了该部门数据
     *
     * @return
     */
    private boolean checkOrgLoad(OrgDeptUserBean bean) {
        for (Map.Entry<String, List<OrgDeptUserBean>> entry : orgLoadMap.entrySet()) {
            if (entry.getKey().equals(bean.dept_id)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onEventMainThread(Map inParam) {
        super.onEventMainThread(inParam);
        if (inParam.get(EventBusConstant.TYPE) == null) {
            return;
        }
        String type = inParam.get(EventBusConstant.TYPE).toString();
        String userId = (String) inParam.get(EventBusConstant.OPERATE_ID);

        LogUtil.d(TAG, "wubaojie>>>onEventMainThread: type:" + type + " id:" + userId);
        if (type.equals(EventBusConstant.ACTIVITY_TO_ORGANIZATION)) {
            if (!isInit) {
                saveUndealUser.remove(userId); //界面还未初始化时,传过来的数据无法处理
                return;
            }
            //两个个key
            //取消某一个
//            updateListviewItem(id, false);
            updateListView(userId, false);
            judgeParentSelectStatus(userId, false);
            if (orgListAdpter != null)
                orgListAdpter.notifyDataSetChanged();

        } else if (type.equals(EventBusConstant.ADDRESSBOOK_TO_ORGANIZATION)) {

            //三个key
            //选中或者取消某一个
            boolean isSelectCancel = (Boolean) inParam.get(EventBusConstant.SELECT_OR_CANCEM);
            if (!isInit) {
                if (isSelectCancel) {
                    saveUndealUser.add(userId); //界面还未初始化时,传过来的数据无法处理
                    return;
                } else {
                    saveUndealUser.remove(userId);
                    return;
                }
            }
//            updateListviewItem(id, isSelectCancel);
            updateListView(userId, isSelectCancel);
            judgeParentSelectStatus(userId, isSelectCancel);
            if (orgListAdpter != null)
                orgListAdpter.notifyDataSetChanged();
        }



    }

    private void updateListView(String user_id, boolean isChecked) {
        if (mDataList == null) {
            return;
        }
        for (OrgDeptUserBean bean : mDataList) {
            if (bean.user_id.equals(user_id)) {
                bean.isSelectd = isChecked;
            }
        }
    }

    /**
     * 判断是否为删除员工
     *
     * @return
     */
    private boolean isAddMember() {
        if (ChatInfoActivity.MEMBER_ADD.equals(fromType)) {
            return true;
        }
        return false;
    }


    /**
     * 更新某个item
     *
     * @param id
     * @param state
     */
    private void updateListviewItem(String id, boolean state) {
        if (orgListAdpter == null) {
            return;
        }
//        List<Node> nodeList = orgListAdpter.getVisibleNodes();
//
//        int position = 0;
//        for (int i = 0; i < nodeList.size(); i++) {
//            Node mNode = nodeList.get(i);
//            if (id != null && id.equals(mNode.getId())) {
//                ((OrgDeptUserBean) mNode.getObject()).isSelectd = state;
//                position = i;
//                break;
//            }
//        }
//        LogUtil.d("找到的postion>>>" + position);
////        bean.isSelectd = false;
//        int visiblePostion = dataListview.getFirstVisiblePosition();
//        LogUtil.d(visiblePostion + "");
//        if (position - visiblePostion >= 0) {
//            View view = dataListview.getChildAt(position - visiblePostion).findViewById(R.id.check_select);
//            if (view != null && view instanceof CheckBox) {
//                ((CheckBox) view).setChecked(state);
//            }
//        }

        String pId = "";
        for (Map.Entry<String, List<OrgDeptUserBean>> entry : userListMap.entrySet()) {
            for (OrgDeptUserBean bean : entry.getValue()) {
                if (id.equals(bean.user_id)) {
                    pId = entry.getKey();
                    break;
                }
            }
            if (!TextUtils.isEmpty(pId)) {
                break;
            }
        }

        List<OrgDeptUserBean> allUser = new ArrayList<>();
        for (OrgDeptUserBean deptUserBean : mDataList) {
            if (!deptUserBean.isLeaf && deptUserBean.dept_pid.equals(pId)) {
                //找到某个部门的所有子节点
                allUser.addAll(userListMap.get(pId));

            }
        }
        boolean isAllopeate = true;
        for (OrgDeptUserBean bean : allUser) {
            if (state) {
                if (!bean.isSelectd) {
                    isAllopeate = false;
                    break;
                }
            }
            if (!state) {
                if (bean.isSelectd) {
                    isAllopeate = false;
                    break;
                }
            }
        }

        if (isAllopeate) {
            for (OrgDeptUserBean bean : mDataList) {
                if (bean.dept_id.equals(pId + "allSelect")) {
                    bean.isSelectd = state;
                }
            }
        }


    }
}
